﻿using System;
using System.IO;
using System.Net;
using System.Linq;
using System.Xml.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Windows.Media.Imaging;
using System.Windows.Media.Animation;
using System.Threading;
using System.ComponentModel;
using System.IO.IsolatedStorage;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using Microsoft.Phone.Notification;
using CommonControls;
using Common.Library;
using OnlineVideos.Common;
using OnlineVideos.Data;
using OnlineVideos.UI;
using OnlineVideos.Library;
using Common.Utilities;
using Common;
using OnlineVideos.Utilities;
using Microsoft.Phone.BackgroundAudio;
using SyncStories;
using AdRotator;
using System.Windows.Controls.Primitives;
using Windows.Storage;
using System.Threading.Tasks;
using Windows.ApplicationModel;
using Windows.Phone.Speech.Recognition;
using Windows.Phone.Speech.Synthesis;
using Windows.Foundation;
using OnlineVideos.Entities;
using System.Globalization;
using Microsoft.Advertising.Mobile.UI;
using System.ServiceModel.Syndication;
using OnlineVideos.ViewModels;
using Microsoft.Phone.Shell;

namespace OnlineVideos
{    
    public partial class MainPage : PhoneApplicationPage
    {
        #region GlobalDeclaration
        DispatcherTimer dt = new DispatcherTimer();
        IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
        ObservableCollection<ShowList> objtoprated = null;
        ObservableCollection<ShowList> objRecent = null;
        ObservableCollection<ShowList> objtamil = null;
        ObservableCollection<ShowList> objupcoming = null;
        SpeechRecognizer _myRecognizer;
        SpeechSynthesizer _synthesizer;
        IAsyncOperation<SpeechRecognitionResult> _recoOperation;
        Dictionary<string, Uri> Navigation;
        SpeechRecognizerUI speechRecognizer;
        string link;

        #endregion

        #region Constructor

        public MainPage()
        {
            InitializeComponent();
            RununderLockscreen();
            InitializeUI();
            try
            {
                this.speechRecognizer = new SpeechRecognizerUI();
            }
            catch (Exception ex)
            {
                string excee = ex.Message;
            }
            Unloaded += MainPage_Unloaded;
        }

        void MainPage_Unloaded(object sender, RoutedEventArgs e)
        {
            try
            {
                if (UtilitiesResources.ShowAdRotator)
                {
                    //Border frameBorder = (Border)VisualTreeHelper.GetChild(Application.Current.RootVisual, 0);
                    //AdControl Adc = frameBorder.FindName("AdRotatorWin8") as AdControl;
                    //Adc.Visibility = Visibility.Visible;                  
                }
            }
            catch (Exception ex)
            {
                string excep = ex.Message;
            }
        }
        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
          // FlurryWP8SDK.Api.EndTimedEvent("MainPage");
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            try
            {
                if (AppSettings.ProjectName == "Indian Cinema" || AppSettings.ProjectName == "Indian Cinema Pro")
                {
                    tblkhindi.Text = "hindi";
                    tblktelugu.Text = "telugu";
                    pvtitmtamil.Visibility = Visibility.Visible;
                    pvtitmupcoming.Visibility = Visibility.Visible;
                }
                else
                {
                    tblkhindi.Text = "top rated";
                    tblktelugu.Text = "recent";
                    pvtitmtamil.Visibility = Visibility.Collapsed;
                    pvtitmupcoming.Visibility = Visibility.Collapsed;
                }
              //  FlurryWP8SDK.Api.LogPageView();
                if (UtilitiesResources.ShowAdRotator)
                {
                    Border frameBorder = (Border)VisualTreeHelper.GetChild(Application.Current.RootVisual, 0);
                    AdRotatorControl Adc = frameBorder.FindName("AdRotatorWin8") as AdRotatorControl;
                    Adc.IsAdRotatorEnabled = false;
                    Adc.Visibility = Visibility.Collapsed;
                }
                if (AppSettings.AddNewShowIconVisibility)
                {
                    string backentryid = string.Empty;
                    if (NavigationContext.QueryString.TryGetValue("backentryid", out backentryid))
                    {
                        PageHelper.RemoveEntryFromBackStack("MainPage.xaml");
                    }
                }
            }
            catch (Exception ex)
            {

            }

            //TODO: figure our what this code is for?
            if (this.NavigationContext.QueryString.Keys.Contains("MovieName"))
            {
                try
                {
                    PanoramaItem pi = new PanoramaItem();
                    pi.Header = "QuickCard";
                    var grid = new Grid();
                    StackPanel s = new StackPanel();
                    TextBlock t1 = new TextBlock();
                    t1.Name = "txtproduct";
                    TextBlock t2 = new TextBlock();
                    t2.Name = "txtyes";
                    TextBlock t3 = new TextBlock();
                    t3.Name = "txtno";
                    s.Children.Add(t1);
                    s.Children.Add(t2);
                    s.Children.Add(t3);
                    grid.Children.Add(s);
                    pi.Content = grid;
                    panoramaMain.Items.Add(pi);

                    string productName = this.NavigationContext.QueryString["MovieName"];
                    t1.Text = productName;
                    if (IsLikeable(productName))
                    {
                        t2.Text = "yes";
                    }
                    else
                    {
                        t3.Text = "no";
                    }
                }
                catch (Exception ex)
                {
                    string exce = ex.Message;
                }
            }
        }

        private bool IsLikeable(string productName)
        {
            Random rand = new Random(productName.Length);
            int test = rand.Next() & 1;
            return test == 1;

        }

        #endregion

        #region PageLoad
        
        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
              //  FlurryWP8SDK.Api.LogEvent("MainPage", true);
                //SyncButton.Login();
                
              
              if (ResourceHelper.ProjectName == "Web Tile")
              {

                  dt.Interval = TimeSpan.FromSeconds(40);
                  dt.Tick += dt_Tick;
                  dt.Start();

              }
                if (ResourceHelper.ProjectName == AppResources.VideoMix)
                {                  
                    downloadimg.Visibility = Visibility.Visible;
                }
                SearchPanel.Visibility = Visibility.Visible;
                GetPageDataInBackground();
                if (!AppSettings.LiveTileBackgroundAgentStatus)
                {
                    GetLiveTileImagesInBackGround();
                }
                //if (UtilitiesResources.ShowAdRotator)
                //{
                //    Border frameBorder = (Border)VisualTreeHelper.GetChild(Application.Current.RootVisual, 0);
                //    AdControl Adc = frameBorder.FindName("AdRotatorWin8") as AdControl;                    
                //    App.AdStatus = true;
                //}            
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in PhoneApplicationPage_Loaded Method In MainPage file.", ex);
            }
        }

        void dt_Tick(object sender, EventArgs e)
        {
            BackGroundCheck bc = new BackGroundCheck();
            AddReminder ar = new AddReminder();
            object[] ob = new object[2];
            ob[0] = ar;
            ob[1] = bc;
            ar.timer = dt;
            bc.timer = dt;
            BackgroundWorker bg = new BackgroundWorker();
            bg.DoWork += bg_DoWork;
            bg.RunWorkerAsync(ob);
        }

        void bg_DoWork(object sender, DoWorkEventArgs e)
        {
            object[] ob = (object[])e.Argument;
            ((BackGroundCheck)ob[1]).CheckData();
            ((AddReminder)ob[0]).Add();
        }
       
        void RegisterShowDownloadAgent(object sender, EventArgs e)
        {
            try
            {
                RegisterAgent objbackagent = new RegisterAgent();
                objbackagent.backagent();
                (sender as DispatcherTimer).Stop();
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in ShowDownloadAgentTimer_Tick Method In MainPage file.", ex);
            }
        }

        #endregion

        #region Events


        private void lbxTopRated_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                lbxRecentlyAdded_SelectionChanged(sender, e);
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in lbxTopRated_SelectionChanged event In MainPage file.", ex);
            }
        }

        private void lbxRecentlyAdded_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                ListBox MainPageListBox = sender as ListBox;
                
                if (MainPageListBox.SelectedIndex == -1)
                    return;
                if ((MainPageListBox.SelectedItem as ShowList).Rating != null)
                    AppSettings.ShowRating = (double)Math.Round(Convert.ToDecimal((MainPageListBox.SelectedItem as ShowList).Rating));
                AppSettings.ShowID = (MainPageListBox.SelectedItem as ShowList).ShowID.ToString();
                AppSettings.Title = (MainPageListBox.SelectedItem as ShowList).Title;
                AppState.searchtitle = "";

                string ext = System.IO.Path.GetExtension((MainPageListBox.SelectedItem as ShowList).Title);
                if (ext == ".3gp" || ext == ".3g2" || ext == ".mp4" || ext == ".m4v" || ext == ".wmv" || (MainPageListBox.SelectedItem as ShowList).TileImage == "videos.jpg")
                {
                    DownloadManagerHelper.Playvideo(int.Parse(AppSettings.ShowID));

                }
                else if (ext == ".mp3" || ext == ".wav" || ext == ".aac" || ext == ".amr" || ext == ".wma")
                {
                    LoadAudioSongd((MainPageListBox.SelectedItem as ShowList).Title);
                }
                else if (ext == ".jpg" || ext == ".png")
                {

                    PageHelper.NavigateToDownloadedImagePage(AppResources.DownloadImagePageName);
                }
                else
                {
                    PageHelper.NavigateToDetailPage(AppResources.DetailPageName, AppSettings.ShowID);
                   
                }
                MainPageListBox.SelectedIndex = -1;
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in lbxRecentlyAdded_SelectionChanged event In MainPage file.", ex);
            }
        }

        private void lbxMenu_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (lbxMenu.SelectedIndex == -1)
                    return;

                switch ((lbxMenu.SelectedItem as MenuProperties).Id)
                {
                    case "1":
                        NavigationService.Navigate(NavigationHelper.getShowListPage((lbxMenu.SelectedItem as MenuProperties).Name));
                        break;
                    case "2":
                        PageHelper.NavigateToOnlineWebTile(AppResources.OnlinewebTilePageName);
                        break;
                    case "3":
                        PageHelper.NavigateToFavoritePage(AppResources.FavoritePageName);
                        break;
                    case "4":
                        PageHelper.NavigateToHistoryPage(AppResources.HistoryPageName);
                        break;
                    case "5":
                        NavigationService.Navigate(NavigationHelper.HelpMenuPage);
                        break;
                    case "6":
                        NavigationService.Navigate(NavigationHelper.SettingsPage);
                        break;
                }

                lbxMenu.SelectedIndex = -1;
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in lbxMenu_SelectionChanged event In MainPage file.", ex);
            }
        }

        private void imgSearch_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            LaunchSearchPage();
        }

        private void tbxSearch_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                LaunchSearchPage();
            }
        }

        private void lbxSongsList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (lbxSongsList.SelectedIndex == -1)
                    return;
                AppState.searchtitle = (lbxSongsList.SelectedItem as ShowLinks).Title;
                AppSettings.ShowID = (lbxSongsList.SelectedItem as ShowLinks).ShowID.ToString();
                Constants.topsongnavigation = "3";
                PageHelper.NavigateToDetailPage(AppResources.DetailPageName, AppSettings.ShowID);


                lbxSongsList.SelectedIndex = -1;
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in lbxSongsList_SelectionChanged event In MainPage file.", ex);
            }
        }
        private void lbxAudioList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (lbxAudioList.SelectedIndex == -1)
                return;
            AppSettings.ShowID = (lbxAudioList.SelectedItem as ShowLinks).ShowID.ToString();
            AppState.searchtitle = (lbxAudioList.SelectedItem as ShowLinks).Title.ToString();
            if(ResourceHelper.AppName==Apps.Bollywood_Music.ToString())
                Constants.topsongnavigation = "1";
            else
            Constants.topsongnavigation = "4";
            PageHelper.NavigateToDetailPage(AppResources.DetailPageName, AppSettings.ShowID);
            lbxAudioList.SelectedIndex = -1;
        }

        private void downloadimg_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (ResourceHelper.ProjectName == AppResources.VideoMix)
            {
                NavigationService.Navigate(NavigationHelper.CreatePlayListPage);
                Constants.UpdatePlayListTitleAndDescrption = false;
            }
            else
            {
                NavigationService.Navigate(NavigationHelper.BrowserPage);
            }
        }

        #endregion

        #region "Common Methods"

        private void GetPageDataInBackground()
        {
            BackgroundHelper bwHelper = new BackgroundHelper();
           
            bwHelper.AddBackgroundTask(
                                        (object s, DoWorkEventArgs a) =>
                                        {

                                            a.Result =App.group;
                                        },
                                        (object s, RunWorkerCompletedEventArgs a) =>
                                        {
                                            objtoprated = (ObservableCollection<ShowList>)a.Result;
                                            if (objtoprated.Count != 0)
                                            {
                                                lbxTopRated.ItemsSource = objtoprated;
                                                tblkToprated.Visibility = Visibility.Collapsed;
                                            }
                                            else
                                            {
                                                lbxTopRated.ItemsSource = null;
                                                if (ResourceHelper.ProjectName == "Web Tile")
                                                    tblkToprated.Text = AppResources.TopRatedMsg;
                                                if (ResourceHelper.AppName == Apps.Video_Mix.ToString() || ResourceHelper.AppName == Apps.Web_Tile.ToString())
                                                tblkToprated.Visibility = Visibility.Visible;
                                            }
                                        }
                                      );

            bwHelper.AddBackgroundTask(
                                        (object s, DoWorkEventArgs a) =>
                                        {

                                            a.Result = App.grouptelugu;
                                        },
                                        (object s, RunWorkerCompletedEventArgs a) =>
                                        {
                                            objRecent = (ObservableCollection<ShowList>)a.Result;
                                            if (objRecent.Count != 0)
                                            {
                                                lbxRecentlyAdded.ItemsSource = objRecent;
                                                tblkrecent.Visibility = Visibility.Collapsed;
                                               
                                            }
                                            else
                                            {
                                                lbxRecentlyAdded.ItemsSource = null;
                                                if (ResourceHelper.ProjectName == "Web Tile")
                                                    tblkrecent.Text = AppResources.RecentdMsg;
                                                if (ResourceHelper.AppName == Apps.Video_Mix.ToString() || ResourceHelper.AppName == Apps.Web_Tile.ToString())
                                                tblkrecent.Visibility = Visibility.Visible;
                                            }
                                            
                                        }
                                      );
            if (AppSettings.ProjectName == "Indian Cinema" || AppSettings.ProjectName == "Indian Cinema Pro")
            {
                bwHelper.AddBackgroundTask(
                                           (object s, DoWorkEventArgs a) =>
                                           {

                                               a.Result = OnlineShow.GetTamilAddedShows().Items;
                                           },
                                           (object s, RunWorkerCompletedEventArgs a) =>
                                           {
                                               objtamil = (ObservableCollection<ShowList>)a.Result;
                                               if (objtamil.Count != 0)
                                               {
                                                   lbxtamil.ItemsSource = objtamil;
                                                   //tblkrecent.Visibility = Visibility.Collapsed;

                                               }
                                               else
                                               {
                                                   lbxtamil.ItemsSource = null;
                                                   //if (ResourceHelper.ProjectName == "Web Tile")
                                                   //    tblkrecent.Text = AppResources.RecentdMsg;
                                                   //if (ResourceHelper.AppName == Apps.Video_Mix.ToString() || ResourceHelper.AppName == Apps.Web_Tile.ToString())
                                                   //    tblkrecent.Visibility = Visibility.Visible;
                                               }

                                           }
                                         );
            }
            if (AppSettings.ProjectName == "Indian Cinema" || AppSettings.ProjectName == "Indian Cinema Pro")
            {
                bwHelper.AddBackgroundTask(
                                          (object s, DoWorkEventArgs a) =>
                                          {

                                              a.Result = OnlineShow.GetUpComingMovies().Items;
                                          },
                                          (object s, RunWorkerCompletedEventArgs a) =>
                                          {
                                              objupcoming = (ObservableCollection<ShowList>)a.Result;
                                              if (objupcoming.Count != 0)
                                              {
                                                  lbxupcoming.ItemsSource = objupcoming;
                                                  //tblkrecent.Visibility = Visibility.Collapsed;

                                              }
                                              else
                                              {
                                                  lbxupcoming.ItemsSource = null;
                                                  //if (ResourceHelper.ProjectName == "Web Tile")
                                                  //    tblkrecent.Text = AppResources.RecentdMsg;
                                                  //if (ResourceHelper.AppName == Apps.Video_Mix.ToString() || ResourceHelper.AppName == Apps.Web_Tile.ToString())
                                                  //    tblkrecent.Visibility = Visibility.Visible;
                                              }

                                          }
                                        );
            }
            bwHelper.AddBackgroundTask(
                                        (object s, DoWorkEventArgs a) =>
                                        {
                                            a.Result = OnlineVideos.UI.MenuHelper.GetMainMenuItems((string)a.Argument);
                                        },
                                        (object s, RunWorkerCompletedEventArgs a) =>
                                        {
                                            List<MenuProperties> MainmenuItems = (List<MenuProperties>)a.Result;
                                            if (!AppResources.ShowonlinewebTile)
                                            {
                                                MainmenuItems.RemoveAt(1);
                                            }
                                            lbxMenu.ItemsSource = MainmenuItems;
                                        },
                                        (object)AppResources.MainMenuItemShowListName
                                      );

            if (AppResources.ShowTopRatedLinks)
            {
                bwHelper.AddBackgroundTask(
                                            (object s, DoWorkEventArgs a) =>
                                            {
                                                a.Result = OnlineShow.GetTopRatedLinks();
                                            },
                                            (object s, RunWorkerCompletedEventArgs a) =>
                                            {
                                                lbxSongsList.ItemsSource = (List<ShowLinks>)a.Result;
                                            }
                                          );
            }
            if (AppResources.ShowTopRatedAudioLinks)
            {
                bwHelper.AddBackgroundTask(
                                            (object s, DoWorkEventArgs a) =>
                                            {
                                                a.Result = OnlineShow.GetTopRatedAudioLinksforXml();
                                            },
                                            (object s, RunWorkerCompletedEventArgs a) =>
                                            {
                                                lbxAudioList.ItemsSource = (List<ShowLinks>)a.Result;
                                            }
                                          );
            }
            bwHelper.RunBackgroundWorkers();

            if (!Storage.IsLowMemDevice)
            {
                if (AppResources.RegisterDownloadAgent)

                    bwHelper.AddScheduledBackgroundTask(RegisterShowDownloadAgent, TimeSpan.FromSeconds(10));
                bwHelper.StartScheduledTasks();
            }

           
        }

        private void GetPageDataSynchronously()
        {
            lbxTopRated.ItemsSource = OnlineShow.GetTopRatedShows().Items;
            lbxRecentlyAdded.ItemsSource = OnlineShow.GetRecentlyAddedShows().Items;
            lbxMenu.ItemsSource = OnlineVideos.UI.MenuHelper.GetMainMenuItems(AppResources.MainMenuItemShowListName);
            if (AppResources.ShowTopRatedLinks)
            {
                lbxSongsList.ItemsSource = OnlineShow.GetTopRatedLinks();
            }
        }

        private void LaunchSearchPage()
        {
            if (tbxSearch.Text != "")
            {
                NavigationService.Navigate(NavigationHelper.getSearchPage(tbxSearch.Text.ToLower()));
                SearchManager.SaveSearchHistoryIntoDatabase(tbxSearch.Text.ToLower());
                //tblkSearchVal.Visibility = Visibility.Collapsed;
            }
            else
            {
                //tblkSearchVal.Visibility = Visibility.Visible;
            }
        }

        private void InitializeUI()
        {
           
                if (AppResources.ShowTopRatedLinks && AppResources.ShowDetailPageAudioPivot)
                {
                    PvtitmTopSongs.Visibility = Visibility.Visible;
                    tblkMusicHeader.Text = "top music";
                    PvtitmTopAudio.Visibility = Visibility.Visible;
                    tblkHeader.Text = AppResources.TopRatedLinksTitle;
                    AppSettings.musicvisibility = PvtitmTopAudio.Visibility.ToString();
                }
                else if (!AppResources.ShowTopRatedLinks && AppResources.ShowDetailPageAudioPivot)
                {
                    if (AppSettings.AddNewShowIconVisibility)
                    {
                        PvtitmTopSongs.Visibility = Visibility.Collapsed;
                        PvtitmTopAudio.Visibility = Visibility.Collapsed;
                    }
                    else
                    {
                        PvtitmTopSongs.Visibility = Visibility.Collapsed;
                        tblkMusicHeader.Text = "top music";
                        PvtitmTopAudio.Visibility = Visibility.Visible;
                    }
                }
                else
                {
                    PvtitmTopSongs.Visibility = Visibility.Collapsed;
                    PvtitmTopAudio.Visibility = Visibility.Collapsed;
                }

                if (AppSettings.AddNewShowIconVisibility)
                {
                    downloadimg.Visibility = Visibility;
                }
                if (AppResources.ShowTopRatedLinks)
                    PvtitmTopSongs.Visibility = Visibility.Visible;
                else
                    PvtitmTopSongs.Visibility = Visibility.Collapsed;
            
           
        }

        private void GetLiveTileImagesInBackGround()
        {
           
            BackgroundHelper bwHelper = new BackgroundHelper();
            //PrimaryTileUpdate primarytileupdate = new PrimaryTileUpdate();
            bwHelper.AddBackgroundTask(
                                        (object s, DoWorkEventArgs a) =>
                                        {
                                            Constants.LiveTileBackgroundAgentStatus = false;
                                           // primarytileupdate.LiveTileUpdate(ResourceHelper.ProjectName);
                                            LiveTileUpDate.LiveTileForCycle();
                                            //LiveTileUpDate.CreateOrUpDateTile();
                                        },
                                        (object s, RunWorkerCompletedEventArgs a) =>
                                        {

                                        }
                                      );
            bwHelper.RunBackgroundWorkers();
        }

        #endregion

        private void LoadAudioSongd(string title)
        {                          
            int Showid = Convert.ToInt32(AppSettings.ShowID);
            string linktpe = LinkType.Audio.ToString();
            var ShowLinksByType = Task.Run(async () => await Constants.connection.Table<ShowLinks>().Where(i => i.ShowID == Showid && i.LinkType == linktpe).ToListAsync()).Result;
            foreach (var linkinfo in ShowLinksByType)
            {
                if (linkinfo.Title == title)
                {
                    AudioTrack audioTrack = new AudioTrack();
                    audioTrack.BeginEdit();
                    audioTrack.Source = new Uri(linkinfo.LinkUrl, UriKind.RelativeOrAbsolute);
                    audioTrack.Title = linkinfo.Title;
                    audioTrack.EndEdit();
                    BackgroundAudioPlayer.Instance.Track = audioTrack;
                    BackgroundAudioPlayer.Instance.Play();
                    BackgroundAudioPlayer.Instance.PlayStateChanged += new EventHandler(Instance_PlayStateChanged);
                    AppSettings.AudioShowID = AppSettings.ShowID;
                }
                else
                {
                    BackgroundAudioPlayer.Instance.Pause();
                    AppSettings.SongPlayImage = string.Empty;
                }
            }
        }

        void Instance_PlayStateChanged(object sender, EventArgs e)
        {          
            PlayState playState = BackgroundAudioPlayer.Instance.PlayerState;
            switch (playState)
            {
                case PlayState.Paused:
                    IEnumerable<DependencyObject> cboxes = PageHelper.GetChildsRecursive(lbxRecentlyAdded);
                    foreach (DependencyObject obj in cboxes.OfType<PerformanceProgressBar>())
                    {
                        Type type = obj.GetType();
                        if (type.Name == "PerformanceProgressBar")
                        {
                            PerformanceProgressBar cb = obj as PerformanceProgressBar;
                            if (cb.Tag.ToString() == AppSettings.ShowLinkTitle)
                            {
                                cb.IsIndeterminate = false;
                            }
                        }
                    }
                    break;

                case PlayState.Playing:

                    IEnumerable<DependencyObject> cboxes1 = PageHelper.GetChildsRecursive(lbxRecentlyAdded);
                    foreach (DependencyObject obj in cboxes1.OfType<PerformanceProgressBar>())
                    {
                        Type type = obj.GetType();
                        if (type.Name == "PerformanceProgressBar")
                        {
                            PerformanceProgressBar cb = obj as PerformanceProgressBar;
                            if (cb.Tag.ToString() == AppSettings.ShowLinkTitle)
                            {
                                cb.IsIndeterminate = false;
                            }
                        }
                    }
                    break;
            }
        }

        private void RununderLockscreen()
        {
            bool AppLevelState = true;
            if (settings.Contains("AppLevelState"))
                AppLevelState = Convert.ToBoolean(settings["AppLevelState"]);
            if (settings.Contains("runUnderLock"))
                ApplicationIdleModeHelper.Current.RunsUnderLock = SettingsHelper.getBoolValue("runUnderLock");
            //ApplicationIdleModeHelper.Current.RunsUnderLock = IdleDetectionMode.Disabled;
            if (AppLevelState == true)
            {
                MessageBoxResult resultLocService = MessageBox.Show("In order to deliver location tracking services and relevent Ads for your location, application needs permission to use the location services on the device.\n\n\n Do you want to allow application to use location service?", "Location Service", MessageBoxButton.OKCancel);
                if (resultLocService == MessageBoxResult.OK)
                {
                    SettingsHelper.Save("GeoLocationStatus", "true");

                    MessageBoxResult resultRunUnderLock = MessageBox.Show("In order to provide background audio/video playback and download new links in the background, application needs permission to run under the phone lock screen. \n\n\n Do you want to allow application to run under lock screen?", "Run Under Lock Screen", MessageBoxButton.OKCancel);

                    if (resultRunUnderLock == MessageBoxResult.OK)
                    {
                        ApplicationIdleModeHelper.Current.HasUserAgreedToRunUnderLock = true;
                        SettingsHelper.Save("runUnderLock", "true");
                        ApplicationIdleModeHelper.Current.RunsUnderLock = true;
                    }
                    else
                    {
                        ApplicationIdleModeHelper.Current.RunsUnderLock = false;
                        SettingsHelper.Save("runUnderLock", "false");
                    }
                }
                else
                    SettingsHelper.Save("GeoLocationStatus", "false");

                SettingsHelper.Save("AppLevelState", "false");
            }
        }

        private async void speaker_Click_1(object sender, RoutedEventArgs e)
        {
        }

        private void Search_ActionIconTapped(object sender, EventArgs e)
        {
            LaunchSearchPage();
        }

        private async void speaker_MouseLeftButtonDown_1(object sender, MouseButtonEventArgs e)
        {
            try
            {
                this.speechRecognizer.Recognizer.Grammars.Clear();
                Uri citiesGrammar = new Uri("ms-appx:///DefaultData/SpeechTitles.xml", UriKind.Absolute);
                this.speechRecognizer.Recognizer.Grammars.AddGrammarFromUri("Cities", citiesGrammar);
                await this.speechRecognizer.Recognizer.PreloadGrammarsAsync();
                try
                {
                    // Use the built-in UI to prompt the user and get the result.
                    SpeechRecognitionUIResult recognitionResult = await this.speechRecognizer.RecognizeWithUIAsync();

                    if (recognitionResult.ResultStatus == SpeechRecognitionUIStatus.Succeeded)
                    {
                        tbxSearch.Text = recognitionResult.RecognitionResult.Text.Replace(".", string.Empty);
                        string searchText = tbxSearch.Text;
                        List<ShowList> showLinks = SearchManager.GetShowsBySearch(searchText);
                        foreach (ShowList objLinks in showLinks)
                        {
                            if (tbxSearch.Text == objLinks.Title)
                            {
                                AppSettings.ShowID = (objLinks.ShowID).ToString();
                                PageHelper.NavigateToDetailPage(AppResources.DetailPageName, AppSettings.ShowID);
                            }
                        }
                        string SearchText = tbxSearch.Text.Replace(".", string.Empty);
                        if (SearchText == "Favorites")
                        {
                            if (ResourceHelper.ProjectName == "Vedic Library")
                            {
                                NavigationService.Navigate(new Uri("/Views/StoryTimeFavorite.xaml", UriKind.Relative));
                            }
                            else if (ResourceHelper.ProjectName == "Indian Cinema" || ResourceHelper.ProjectName == "Indian Cinema Pro")
                            {
                                NavigationService.Navigate(new Uri("/Views/MoviesFavorites.xaml", UriKind.Relative));
                            }
                            else
                            {
                                NavigationService.Navigate(new Uri("/Views/ShowFavorites.xaml", UriKind.Relative));
                            }
                        }
                        if (SearchText == "Movie list" || SearchText == "vedic library" || SearchText == "yoga shows")
                        {
                            NavigationService.Navigate(new Uri("/Views/ShowList.xaml", UriKind.Relative));
                        }
                        if (SearchText == "History")
                        {
                            if (ResourceHelper.ProjectName == "Vedic Library")
                            {
                                NavigationService.Navigate(new Uri("/Views/StoryTimeHistory.xaml", UriKind.Relative));
                            }
                            else if (ResourceHelper.ProjectName == "Indian Cinema" || ResourceHelper.ProjectName == "Indian Cinema Pro")
                            {
                            NavigationService.Navigate(new Uri("/Views/MoviesHistory.xaml", UriKind.Relative));
                            }
                            else
                            {
                                NavigationService.Navigate(new Uri("/Views/ShowHistory.xaml", UriKind.Relative));
                            }
                        }
                        if (SearchText == "Help")
                        {
                            NavigationService.Navigate(NavigationHelper.HelpMenuPage);
                        }
                        if (recognitionResult.ResultStatus == SpeechRecognitionUIStatus.Succeeded)
                        {
                            NavigationService.Navigate(NavigationHelper.getSearchPage(tbxSearch.Text));
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void lbxtamil_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            lbxRecentlyAdded_SelectionChanged(sender, e);
        }

        private void lbxupcoming_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            lbxRecentlyAdded_SelectionChanged(sender, e);
        }

        private void playfav_MouseLeftButtonDown_1(object sender, MouseButtonEventArgs e)
        {
            Constants.YoutubePlayList = new Dictionary<string, string>();
            var Itemcollection=Task.Run(async()=>await Constants.connection.Table<ShowLinks>().Where(i => i.IsFavourite ==true && i.LinkType=="Songs").ToListAsync()).Result;
            foreach (var item in Itemcollection)
            {
                if (!Constants.YoutubePlayList.ContainsKey(item.LinkUrl))
                Constants.YoutubePlayList.Add(item.LinkUrl, item.Title);
            }
            if (Constants.YoutubePlayList.Count > 0)
            {               
                if (ResourceHelper.AppName == Apps.Indian_Cinema_Pro.ToString() || ResourceHelper.AppName == Apps.Kids_TV_Pro.ToString() || ResourceHelper.AppName == Apps.Story_Time_Pro.ToString())
                    AppSettings.startplayingforpro = true;
                else
                    AppSettings.startplaying = true;
                AppSettings.LinkUrl = Constants.YoutubePlayList.FirstOrDefault().Key;
                AppSettings.LinkTitle = Constants.YoutubePlayList.FirstOrDefault().Value;
                Constants.YoutubePlayList.Remove(Constants.YoutubePlayList.FirstOrDefault().Key);
                AppSettings.PlayVideoTitle = Constants.YoutubePlayList.FirstOrDefault().Value;
              
                NavigationService.Navigate(new Uri("/Views/Youtube.xaml?myid=" + AppSettings.LinkUrl, UriKind.Relative));
                //YoutubeApi.Youtube.PlayYoutubeVideo(AppSettings.LinkUrl);
            }
        }
    }
}